﻿using System;
using System.Linq;
using System.Windows.Controls;
using jSLCore.Client.Presentation.AuthorizeService;
using jSLCore.Client.Presentation.BaseControl.DialogMessage;
using jSLCore.Client.Presentation.BaseControl.Selection;

namespace jSLCore.Client.Presentation.Authorization.Managment
{
    public partial class PermissionList : SelectControl
    {

        private PermissionDescription[] permissions;

        public PermissionList()
        {
            InitializeComponent();
        }

        public override bool IsStandartOkCancelEnabledWhenNotSelectable
        {
            get { return true; }
        }

        public override void OkClickedWhenNotSelectable()
        {
            DoWork("Сохранение", (sender, args) =>
                                     {
                                         Communication.Proxy.SaveAllPermissions((PermissionDescription[]) args.Params);

                                     }, (o, eventArgs) =>
                                            {
                                                if (eventArgs.Error == null)
                                                {
                                                    InfoBox.ShowDialog("Сохранено");
                                                    InvokeDataSelected();
                                                }
                                            }, permissions);
        }

        public override ISelectableGrid GetSelectableGrid()
        {
            return grid;
        }

        public override void LoadInitialData()
        {
         DoWork("Загрузка прав",(sender, args) =>
                                    {
                                        args.Result = Communication.Proxy.GetAllPermissions();
                                    },(o, eventArgs) =>
                                                          {
                                                              if (eventArgs.Error == null)
                                                              {
                                                                  permissions = (PermissionDescription[]) eventArgs.Result;
                                                                  Search();
                                                              }
                                                          });
            if(SelectionMode!=GridSelectionMode.None)
            {
                grid.IsReadOnly = true;
            }
        }

        private void Search()
        {
            if (permissions != null)
                grid.ItemsSource = permissions.Where(p => p.Name.ToUpper().Contains(txt.Text.ToUpper()));
        }

        public override Control GetControlForInitialFocus()
        {
            return txt;
        }

        protected override void AcceptButtonClicked()
        {
            Search();
        }
    }
}
